package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.auth.utils.JwtUtils;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author 虎哥
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(AuthProperties.class)
public class JwtConfiguration {

    private final AuthClient authClient;

    public JwtConfiguration(AuthClient authClient) {
        this.authClient = authClient;
    }

    @Bean
    public JwtUtils jwtUtils(AuthProperties prop, StringRedisTemplate redisTemplate) throws InterruptedException {
        while (true){
            try {
                // 向ly-auth发送请求，申请秘钥
                String  key = authClient.getJwtKey(prop.getClientId(), prop.getSecret());
                log.info("加载jwt秘钥成功！");
                return new JwtUtils(key, redisTemplate);
            } catch (FeignException e) {
                // 加载秘钥失败，5秒后重试
                log.error("加载jwt秘钥失败了。原因： {}", e.contentUTF8());
                Thread.sleep(5000);
            }
        }
    }
}
